<template>
	<uv-navbar :fixed="false" :title="title" left-arrow @leftClick="$onClickLeft" />
	<view class="order-container">
		<uv-form labelPosition="left" :model="showForm" :rules="rules" ref="formRef" :labelStyle="{marginLeft: '18px'}">
			<uv-form-item label="电站名称" prop="queryObj.powerstationId" @click="showSelect('powerstationId')"
				:labelWidth="labelWidth" borderBottom labelAlign="right">
				<CustomPicker :options="actionOption.stationOption" v-model="showForm.queryObj.powerstationId"
					rangeKey="name" rangeValue="id" :value="showForm.queryObj.powerstationId" @change="stationChange">
					<view class="flex flex-end">
						<uv-icon name="arrow-right" color="#606266"></uv-icon>
					</view>
				</CustomPicker>
			</uv-form-item>
			<uv-form-item label="设备类型" prop="queryObj.deviceType" :labelWidth="labelWidth" borderBottom
				@click="showSelect('deviceType')">

				<CustomPicker :options="actionOption.eqTypeOption" v-model="showForm.queryObj.deviceType"
					rangeKey="name" :value="showForm.queryObj.deviceType" @change="eqTypeChange">
					<view class="flex flex-end">
						<uv-icon name="arrow-right" color="#606266"></uv-icon>
					</view>
				</CustomPicker>
			</uv-form-item>


			<uv-form-item label="设备" prop="queryObj.deviceId" :labelWidth="labelWidth" borderBottom
				@click="showSelect('equipment')">

				<CustomPicker :options="actionOption.equipmentOption" v-model="showForm.queryObj.deviceId"
					rangeKey="name" rangeValue="eqId" :value="showForm.queryObj.deviceId" @change="eqChange">
					<view class="flex flex-end">
						<uv-icon name="arrow-right" color="#606266"></uv-icon>
					</view>
				</CustomPicker>
			</uv-form-item>

			<uv-form-item label="告警" prop="queryObj.alarmId" :labelWidth="labelWidth" borderBottom
				@click="showSelect('alarmId')">

				<CustomPicker :options="actionOption.alarmOption" v-model="showForm.queryObj.alarmId" rangeKey="name"
					:value="showForm.queryObj.alarmId" @change="alarmChange">
					<view class="flex flex-end">
						<uv-icon name="arrow-right" color="#606266"></uv-icon>
					</view>
				</CustomPicker>
			</uv-form-item>
			<uv-form-item label="优先级" prop="queryObj.priority" :labelWidth="labelWidth" borderBottom
				@click="showSelect('priority')">
				<CustomPicker :options="actionOption.priorityOption" v-model="showForm.queryObj.priority"
					rangeKey="name" :value="showForm.queryObj.priority" @change="priorityChange">
					<view class="flex flex-end">
						<uv-icon name="arrow-right" color="#606266"></uv-icon>
					</view>
				</CustomPicker>
			</uv-form-item>


			<uv-form-item label="计划处理开始时间" prop="queryObj.handleDateRange" :labelWidth="labelWidth" borderBottom
				@click="showDateSelect('startTime')">


				<!-- 日期范围搜索 -->
				<uv-datetime-picker ref="startDatetimeRef" mode="datetime" v-model="showForm.queryObj.planStartTime"
					@confirm="confirm"></uv-datetime-picker>
				<view>{{showForm.queryObj.planStartTime}}</view>

				<template v-slot:right>
					<uv-icon name="arrow-right"></uv-icon>
				</template>
			</uv-form-item>
			<uv-form-item label="计划处理结束时间" prop="queryObj.handleDateRange" :labelWidth="labelWidth" borderBottom
				@click="showDateSelect('endTime')">


				<uv-datetime-picker ref="startDatetimeRef" mode="datetime" v-model="showForm.queryObj.planEndTime"
					@confirm="confirm"></uv-datetime-picker>
				<view>{{showForm.queryObj.planEndTime}}</view>

				<template v-slot:right>
					<uv-icon name="arrow-right"></uv-icon>
				</template>
			</uv-form-item>

			<uv-form-item label="工单名称" prop="queryObj.title" :labelWidth="labelWidth" borderBottom>

				<uv-input placeholder="请输入内容" border="surround" v-model="showForm.queryObj.title"></uv-input>
			</uv-form-item>
			<uv-form-item label="工单模版" prop="queryObj.templateId" :labelWidth="labelWidth" borderBottom
				@click="showSelect('orderTemplate')">

				<CustomPicker :options="actionOption.templateOption" v-model="showForm.queryObj.templateId"
					rangeKey="name" rangeValue="id" :value="showForm.queryObj.templateId" @change="templateChange">
					<view class="flex flex-end">
						<uv-icon name="arrow-right" color="#606266"></uv-icon>
					</view>
				</CustomPicker>
			</uv-form-item>

			<uv-form-item label="操作描述" prop="queryObj.description" :labelWidth="labelWidth" borderBottom>
				<uv-textarea v-model="showForm.queryObj.description" placeholder="请输入内容"></uv-textarea>
			</uv-form-item>

			<uv-form-item label="图片" prop="queryObj.fileInfoList" :labelWidth="labelWidth" borderBottom>
				<uv-upload :fileList="fileList" name="1" multiple :maxCount="9" @afterRead="afterRead"
					@delete="deletePic" :previewFullImage="true"></uv-upload>
			</uv-form-item>

			<uv-form-item label="发起人" prop="queryObj.promoter" :labelWidth="labelWidth" borderBottom
				@click="showSelect('promoterName')">
				<uv-input v-model="showForm.queryObj.promoter" disabled disabledColor="#ffffff" placeholder="发起人"
					border="none">
				</uv-input>
				<template v-slot:right>
					<uv-icon name="arrow-right"></uv-icon>
				</template>
			</uv-form-item>

			<!--  -->
			<uv-form-item label="处理人" prop="queryObj.processorId" :labelWidth="labelWidth" borderBottom
				@click="showUserSelect('handlePeosonal')">
				<!-- <uv-input placeholder="请输入内容" border="surround" v-model="showForm.queryObj.processorId" ></uv-input> -->

				<!-- <DaTree ref="DaTreeRef" :data="roomTreeData" labelField="name" valueField="id" defaultExpandAll
					showCheckbox :defaultCheckedKeys="defaultCheckedKeysValue" @change="handleTreeChange"
					@expand="handleExpandChange"></DaTree> -->
				<!-- <custom-tree-select :search="true" :mutiple="false" :listData="listData"
					@selectChange="handleSelectTwo(index, $event)" v-model="showForm.queryObj.processorId"
					:choseParent="false" dataValue="id" dataLabel="littleName" /> -->
			</uv-form-item>
			<uv-form-item label="验证人" prop="queryObj.verifierName" :labelWidth="labelWidth" borderBottom
				@click="showUserSelect('verifierName')">
				<customthree-tree-select :search="true" :mutiple="false" :showChildren="false" :listData="listData"
					dataLabel="label" v-model="showForm.validatorId" />
			</uv-form-item>
			<uv-button type="primary" text="提交" customStyle="margin-top: 10px" @click="submit"></uv-button>
			<uv-button type="info" text="重置" customStyle="margin-top: 10px" @click="reset"></uv-button>
		</uv-form>
		<uv-action-sheet ref="sexSelectRef" :actions="actions" title="请选择数据" @select="sexSelect">
		</uv-action-sheet>

		<uv-popup ref="popupRef" mode="bottom" @change="change">
			<view style="width: 100%;">
				<uv-input type="text" :value="filterValue" @input="handleFilterChange" placeholder="请输入内容筛选" />

				<DaTree ref="DaTreeRef" :data="roomTreeData" labelField="name" valueField="id"
					:filterValue="filterValue" defaultExpandAll showCheckbox
					:defaultCheckedKeys="defaultCheckedKeysValue" @change="handleTreeChange"
					@expand="handleExpandChange"></DaTree>
			</view>
		</uv-popup>

		<uv-datetime-picker ref="endDatetimeRef" mode="datetime" @confirm="endConfirm"></uv-datetime-picker>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		onMounted
	} from "vue"
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		reqQueryList,
		reqEqList
	} from "@/api/model/photovoltaic"
	import {
		VUE_APP_UPLOAD_URL
	} from '@/config';
	// import {
	// 	timestampToDateTime
	// } from "@/utils/common"
	import {
		formatDateTime
	} from '@/utils/util'
	import {
		reqWorkTemplateList,
		reqSubmitWorkTemplate
	} from "@/api/operate"
	import {
		reqPVAlarm
	} from "@/api/alarm"
	import {
		getCurrentInstance
	} from 'vue';

	import {
		reqUserTree
	} from "@/api/system"
	import {
		reqUpload
	} from "@/api/common"
	import DaTree from '@/components/da-tree/index.vue'

	import CustomPicker from "@/components/cus-picker/CusPicker"
	// import CustomTreeSelect from "@/components/customTreeSelect"
	const title = ref('新建工单')
	// 定义一个 ref 来引用子组件
	// key的类型必须对应树数据key的类型
	const defaultCheckedKeysValue = ref(['211', '222'])
	const filterValue = ref('')
	const roomTreeData = ref([{
		id: '2',
		name: '行政中心',
		children: [{
				id: '21',
				name: '行政部',
				children: [{
						id: '211',
						name: '行政一部',
						children: null,
					},
					{
						id: '212',
						name: '行政二部',
						children: [],
						disabled: true,
					},
				],
			},
			{
				id: '22',
				name: '财务部',
				children: [{
						id: '221',
						name: '财务一部',
						children: [],
					},
					{
						id: '222',
						name: '财务二部',
						children: [],
					},
				],
			},
			{
				id: '23',
				name: '人力资源部',
				children: [{
						id: '231',
						name: '人力一部',
						children: [],
					},
					{
						id: '232',
						name: '人力二部',
						append: '更多示例，请下载示例项目查看',
					},
				],
			},
		],
	}, ])
	const popupRef = ref(null);
	const sexSelectRef = ref(null);
	const labelWidth = ref('95')
	const formRef = ref(null)
	let dateRange = ref(null)
	const actionOption = reactive({
		stationOption: [],

	})
	const startDatetimeRef = ref(null)
	const endDatetimeRef = ref(null)
	const testIndex = ref(0)
	const form = reactive({
		queryObj: {
			title: '',


		},
	})
	const instance = getCurrentInstance()

	//展示表单form
	const showForm = reactive({
		queryObj: {
			planStartTime: Number(new Date()),
			planEndTime: Number(new Date())
		}
	})
	const mapKey = ref('')
	const rules = reactive({
		'queryObj.powerstationId': {
			type: 'string',
			required: true,
			message: '请选择电站',
			trigger: ['blur', 'change']
		},
		'queryObj.deviceType': {
			required: true,
			message: '请选择设备类型',
			trigger: ['blur', 'change']
		},
		'queryObj.equipment': {
			required: true,
			message: '请选择设备',
			trigger: ['blur', 'change']
		},


		'queryObj.priority': {
			required: true,
			message: '请选择优先级',
			trigger: ['blur', 'change']
		},
		'queryObj.planStartTime': {
			required: true,
			message: '请选择时间',
			trigger: ['blur', 'change']
		},

		'queryObj.planEndTime': {
			required: true,
			message: '请选择时间',
			trigger: ['blur', 'change']
		},

		'queryObj.title': {
			required: true,
			message: '请输入工单名称',
			trigger: ['blur', 'change']
		},

		'queryObj.templateId': {
			required: true,
			message: '请选择工单模版',
			trigger: ['blur', 'change']
		},

		'queryObj.description': {
			required: true,
			message: '请输入操作描述',
			trigger: ['blur', 'change']
		},





	})
	const actions = ref([])
	const fileList = ref([])
	const datetimePickerRef = ref(null)
	const listData = ref([])

	const handleTreeChange = (allSelectedKeys, currentItem) => {
		console.log('handleTreeChange ==>', allSelectedKeys, currentItem)
	}
	const handleExpandChange = (expand, currentItem) => {
		console.log('handleExpandChange ==>', expand, currentItem)
	}

	const handleFilterChange = (ev) => {
		// console.log('handleFilterChange ==>', ev)
		filterValue.value = ev
	}
	//选中
	const handleSelectTwo = () => {}
	// 提交
	const submit = () => {
		// console.log("提交参数===", showForm)
		// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
		formRef.value.validate().then(async res => {

			showForm.processorId = showForm.processorId.join(',')
			showForm.validatorId = showForm.validatorId.join(',')

			await reqSubmitWorkTemplate(showForm)
			uni.showToast({
				icon: 'success',
				title: '校验通过'
			})
			uni.navigateBack()
		}).catch(errors => {
			uni.showToast({
				icon: 'error',
				title: '校验失败'
			})
		})
	}
	const bindPickerChange = (e) => {
		console.log('picker发送选择改变，携带值为', e.detail.value)
		testIndex.value = e.detail.value

	}
	const afterRead = async (event) => {
		// console.log("event.file===", event)
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = Array.isArray(event.file) ? event.file : [event.file];
		let fileListLen = fileList.value.length;
		lists.forEach((item) => {
			fileList.value.push({
				...item,
				status: 'uploading',

			});
			// message: '上传中'
		});

		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url, lists);
			console.log("返回结果", result)
			let item = fileList.value[fileListLen];
			fileList.value[fileListLen] = {
				...item,
				status: 'success',
				message: '',
				url: result
			};
			fileListLen++;

		}
	}

	const uploadFilePromise = (url, files) => {
		let file = files[0]

		return new Promise((resolve, reject) => {
			let fileName = file.name

			// 将 Blob 转换为 File 对象
			const newFile = new File([file.url], fileName, {
				type: file.type
			});
			let formdata = new FormData();
			formdata.append("file", newFile);
			reqUpload(formdata).then(response => {
				resolve(response.data.url)
			})
		})
	}
	const deletePic = (e) => {
		fileList.value.splice(e.index, 1);
		formRef.value.validateField('pics', err => {
			// 处理错误后的逻辑
		})
	}
	// 重置
	const reset = () => {
		formRef.value.resetFields();
		formRef.value.clearValidate();
	}
	//展示人
	const showUserSelect = async (val) => {
		// let query = {}
		// let {
		// 	data
		// } = await reqUserTree(query)
		// listData.value = data.data
		// console.log("data==", data)
		popupRef.value.open();
	}
	//回写发起人
	const getPromoter = () => {
		let {
			userName
		} = uni.getStorageSync('zh-h5-userInfo')
		showForm.queryObj.promoter = userName


	}
	//通用下拉选择框
	const showSelect = (val) => {
		mapKey.value = val
		getOption(val)
		// sexSelectRef.value.open();
		// hideKeyboard();
	}
	//展开计划处理时间选择
	const showDateSelect = (val) => {
		console.log("日期的", val, datetimePickerRef.value)
		switch (val) {
			case 'startTime':
				startDatetimeRef.value.open();
				break;

			case 'endTime':

				endDatetimeRef.value.open();
				break;
		}

	}

	// 日期确认按钮
	const confirm = async (e) => {
		let time = await formatDateTime(e.value)

		showForm.queryObj.planStartTime = time
	}
	const endConfirm = async (e) => {
		let time = await formatDateTime(e.value)
		showForm.queryObj.planEndTime = time
	}
	//根据选择返回对应下拉框的值
	const getOption = async (val) => {
		const map = {
			'powerstationId': [{
				name: '电站1',
				key: '1'
			}, {
				name: '电站2',
				key: '2'
			}, ],
			'eqType': [{
					name: '类型1',
					key: '1'
				},
				{
					name: '类型2',
					key: '2'
				},
			]
		}
		switch (val) {
			case 'powerstationId':
				let {
					data
				} = await reqQueryList()
				console.log("电站分y", data)
				actionOption.stationOption = data.data
				break;
			case 'deviceType':

				actionOption.eqTypeOption = [{
					value: 'equipment_inverter',
					name: '逆变器'
				}]
				break;


			case 'equipment':

				break;

			case 'eqType':

				actionOption.eqTypeOption = [{
					value: '1',
					name: '逆变器'
				}]
				break;

			case 'priority':
				actionOption.priorityOption = [{
						name: "较低",
						value: 0,
					},
					{
						name: "普通",
						value: 1,
					},
					{
						name: "紧急",
						value: 2,
					},
					{
						name: "非常紧急",
						value: 3,
					},
				]
				break;
			case 'orderTemplate':
				let res = await reqWorkTemplateList()
				actionOption.templateOption = res.data.data.list
				break;

		}
	}
	/**
	 * 电站change事件
	 */
	const stationChange = async (e) => {
		showForm.queryObj.powerstationId = e
	}
	//设备类型查看
	const eqTypeChange = async (e) => {
		showForm.queryObj.deviceType = e
		let {
			data
		} = await reqEqList(e, showForm.queryObj.powerstationId)
		actionOption.equipmentOption = data.data

	}
	const eqChange = async (e) => {
		showForm.queryObj.deviceId = e
		let query = {
			"isPagination": false,
			"orderBy": "create_time desc",
			"queryObj": {
				"equipment": e,
				"alState": 1,
				"dzId": showForm.powerstationId
			}
		}

		let {
			data
		} = await reqPVAlarm(query)
		actionOption.alarmOption = data.data.list

	}
	// 
	const alarmChange = (e) => {
		showForm.queryObj.alarmId = e
		// console.log("告警==", e, showForm.powerstationId)
	}
	const priorityChange = (e) => {
		showForm.queryObj.priority = e
	}
	const templateChange = (e) => {
		showForm.queryObj.templateId = e
	}
	// 性别选择返回结果
	const sexSelect = (e) => {
		// form.queryObj.sex = e.name;
		showForm[mapKey.value] = e.name;
		form.queryObj[mapKey.value] = e.key

		// 对部分表单字段进行校验
		formRef.value.validateField('queryObj.sex', err => {
			// 处理错误后的逻辑
		})
	}



	const hideKeyboard = () => {
		uni.hideKeyboard()
	}

	onMounted(() => {
		getPromoter()
	})

	onLoad(() => {
		console.log("LOAD时间")
		showUserSelect()
		// /对应了 data中的startTime: Number(new Date()),
		//初始化页面时转换时间格式，否则渲染展示的是时间戳
		// showForm.queryObj.planStartTime = formatDateTime(showForm.queryObj.planStartTime);
		// showForm.queryObj.planEndTime = formatDateTime(showForm.queryObj.planEndTime);
	})
</script>

<style lang="scss" scoped>
	.order-container {
		.uv-form {
			::v-deep {
				.uv-form-item__body {
					padding: 10px;
				}

				.select-list {
					width: 100%;
				}
			}
		}
	}
</style>